package cn.edu.sgu.www.mhxysy.util;

import cn.edu.sgu.www.mhxysy.config.property.EmailProperties;
import cn.edu.sgu.www.mhxysy.dto.system.MessageDTO;
import cn.edu.sgu.www.mhxysy.entity.system.Email;
import cn.edu.sgu.www.mhxysy.enums.OpenStatus;
import cn.edu.sgu.www.mhxysy.exception.GlobalException;
import cn.edu.sgu.www.mhxysy.redis.repository.impl.EmailRepository;
import cn.edu.sgu.www.mhxysy.restful.ResponseCode;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 发送邮件的工具类
 * @author 沐雨橙风ιε
 * @version 1.0
 */
@Slf4j
@Component
public class EmailUtils {

    private final EmailSender emailSender;
    private final EmailRepository emailRepository;
    private final EmailProperties emailProperties;

    @Autowired
    public EmailUtils(
            EmailSender emailSender,
            EmailRepository emailRepository,
            EmailProperties emailProperties) {
        this.emailSender = emailSender;
        this.emailRepository = emailRepository;
        this.emailProperties = emailProperties;
    }

    /**
     * 发送邮件，支持批量发送
     * @param text 邮件的内容
     * @param users 接收邮箱
     */
    public void sendMessage(String text, String... users) throws MessagingException {
        MessageDTO messageDTO = new MessageDTO();

        // 未指定邮件接收人
        if (users.length == 0) {
            Subject subject = UserUtils.getSubject();

            // 未登录状态下发送邮件
            if (subject == null) {
                throw new GlobalException(ResponseCode.BAD_REQUEST, "未登录状态下必须指定接收邮箱");
            }

            // 查询用户邮箱信息
            Email email = getEnableEmail(UserUtils.getUserId());
            List<String> list = new ArrayList<>();

            if (email == null) {
                String to = emailProperties.getTo();

                list.add(to);
                log.debug("没有找到用户{}的邮箱，使用系统配置的默认接收邮箱：{}", UserUtils.getLoginUsername(), to);
            } else {
                list.add(email.getAccount());
            }

            messageDTO.setUsers(list);
        } else {
            messageDTO.setUsers(Arrays.asList(users));
        }

        // 设置消息内容
        messageDTO.setContent(text);

        // 发送消息
        emailSender.sendMessage(messageDTO);

        log.debug("邮箱发送成功...");
    }

    /**
     * 获取用户启用中的邮箱信息
     * @param userId 用户ID
     * @return Email 用户的邮箱信息
     */
    public Email getEnableEmail(String userId) {
        List<Email> list = emailRepository.selectById(userId);

        int size = list.size();

        if (size == 1) {
            return list.get(0);
        } else if (size > 1) {
            // 多个邮箱，返回启用的邮箱
            for (Email email : list) {
                if (OpenStatus.OPEN.getValue().equals(email.getState())) {
                    return email;
                }
            }
        }

        return null;
    }

}